package com.luo.comm.services.dingding;

import com.alibaba.fastjson2.JSONObject;

import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SendMessageDing {
    private static final String DINGTALK_WEBHOOK_URL = "https://oapi.dingtalk.com/robot/send?access_token=555d5dbe5236f28f3e0e1d9c873608dcd76323dcd49cd5a8b33c5d84fe9011fd";


    public static void sendMessage(){
//
        try {


            StringBuilder message = new StringBuilder();
            message.append("| 姓名 | 性别  | 年龄 | ");
            message.append("| :-:   | :-:    | :-:  |\n");

            message.append("| 张三 | 男 | 20 |\n");
            JSONObject json = new JSONObject();
            json.put("msgtype", "markdown");
            JSONObject markdown = new JSONObject();
            markdown.put("title", "iuyun提示");
            markdown.put("text", message.toString());
            json.put("markdown", markdown);
            post(DINGTALK_WEBHOOK_URL, json.toString());


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void post(String url, String body) {
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            con.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8);
            writer.write(body);
            writer.flush();
            writer.close();
            int responseCode = con.getResponseCode();
            System.out.println("DingTalkBot: HTTP POST request to " + url + " returned " + responseCode);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

};